/*
 * @Author: xmily
 * @Date: 2021-12-21 09:04:57
 * @LastEditors: xmily
 * @LastEditTime: 2023-02-04 18:20:30
 * @FilePath: \glxxapi\models\Notice\noticeRece.js
 * @Description: 
 * 
 * Copyright (c) 2022 by xmily/mxthink.com.cn, All Rights Reserved. 
 */
//家校通知用户接收表
var mongoose = require('../../cfg/dbconfig.js')

var noticeReceSchema = new mongoose.Schema({
    noticeid: String,
    accountid: String,
    status: String,
    sign: String,
    term:String,
    fundesc:String,
    noticeinfo:Object,
    datetime:Date,
}, { collection: 'noticeRece' })


//根据查询条件获取符合条件的数据
noticeReceSchema.statics.GetOneByQuery=async function(query){
    let result= await this.findOne(query).exec();
    return result
}

//删除符合查询条件的记录
noticeReceSchema.statics.delete=async function(query){
    let result=await this.deleteMany(query).exec();
    return result
}
//更新记录
noticeReceSchema.statics.UpdateStatus=async function(id,noticeid,status){
    let result=await this.updateOne({"accountid":id,"noticeid":noticeid},{$set:{"status":status}})
    return result
}

//存储签名
noticeReceSchema.statics.saveSign=async function(id,sign){
    let result=await this.updateOne({"_id":id},{$set:{"sign":sign,"status":"4已签"}})
    return result
}

//保存签名
noticeReceSchema.statics.Save=async function(doc){
    let obj=new this(doc);
    if(doc._id){
        obj.isNew=false;
    }
    let res=await obj.save();
    return res;
}
//登录用户获取学校通知列表
noticeReceSchema.statics.getNoticeByAccount = async function (condition, sort) {
    let result = await this.aggregate([
        {
            $match: condition
        },
        {
            "$addFields": {
                "objid": {
                    "$toObjectId": "$noticeid"
                }
            }
        },
        {
            $lookup: {
                from: "notice",
                localField: "objid",
                foreignField: "_id",
                as: "noticeinfo"
            }
        },
        {
            $sort: sort
        },
		{
		    $unwind:"$noticeinfo"
		},
        {
            "$addFields": {
                "datetime": {
                    "$toDate": "$objid"
                }
            }
        }
    ]).exec()

    return result;

}

//批量插入通知数据（发送通知给学生）
noticeReceSchema.statics.insertManyDoc=async function(data){
    let result=await this.insertMany(data)
    return result
}

//按条件计数(暂时用aggregate代替)
noticeReceSchema.statics.countByCondition=async function(condition){
    // let result=await this.find(condition).count().exec()
    let result=await this.find(condition).countDocuments().exec()
    return result;
}

noticeReceSchema.statics.countByAggregate=async function(aggregate){
    let result = await this.aggregate(aggregate)
    return result;
}

module.exports=mongoose.model('noticeRece',noticeReceSchema)